package com.love_weinuo.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

import com.tencent.imsdk.TIMManager;
import com.tencent.qcloud.uikit.business.login.view.ILoginEvent;
import com.tencent.qcloud.uikit.business.login.view.LoginView;
import com.tencent.qcloud.uikit.common.utils.UIUtils;
import com.love_weinuo.R;
import com.love_weinuo.bean.Constants;
import com.love_weinuo.ui.view.ILoginView;
import com.love_weinuo.ui.view.chat.PojoLoginPresenter;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by valexhuang on 2018/6/21.
 * <p>
 * Demo的登录Activity，实现了注册逻辑，账号信信息缓存，被踢登录等等，相对复杂
 * <p>
 */

public class IMLoginActivity extends Activity implements ILoginEvent, ILoginView, AdapterView.OnItemSelectedListener, com.love_weinuo.ui.view.chat.ILoginView {

    LoginView mLoginPanel;
    Spinner mSpinner;
    private ArrayAdapter adapter;
    private Button mBtnLoginIm;

    String userId_1 = "vn";
    String userSig_1 = "eJxlj11PgzAUhu-5FYRbjGkLZWPJLjZ0*AGBfcXgTVNHIWfTDrpKRoz-3cg0NvHcPs*b9z0flm3bziZZX-Pd7vguNdN9Ixx7YjvIufqDTQMl45p5qvwHxbkBJRivtFADxJRSgpDpQCmkhgp*jE4a7FQe2FBwCfsI4RBj5JkK1ANMb5fRfdx7yq8L-ujuk75JIHpZy-jhkG0z2tJqPu6KpCXhnXRHixnMaBzuA79eLgIo6WuUtlwF0TO46c0mL*ZP4-zsb7NVvtK8nk6NSg1v4vcbPAo8QsxBnVAnOMpBIAhTTDz0fY71aX0BKxxalg__";

    String userId_2 = "kt";
    String userSig_2 = "eJxlz11PwjAUgOH7-YpmtxrpB5Vp4g1gFOIMy4aGq2ZZy*g*S2lxw-jfjQNjE8-t856cnE8PAOAnL-FNmmWtbQwzvRI*uAc*9K--UCnJWWoY0fwfik5JLVi6NUIPiCilGEK3kVw0Rm7lpSiNYwdesuHAeXkMIbpDCBI3kfmA4eN6tohmyU7AfawjGkf4Wb-z7s1oynu85K-9VbWf1*HqSajEBnW*yPmIdAEaV8WmnVaFtVNakh4d6WY1P32E66jYBXJkl2FWtA-OSSNr8fsNmtySCcSOHoU*yLYZAgwRRZjAn-G9L*8bHklc4Q__";

    String userId_3 = "vic";
    String userSig_3 = "eJxlz01Pg0AQgOE7v2LDtcbusKyxJh6wKVm1pB9gr2Rll3ZCu3x0S7DG-25Em5I41*edTObTIYS4yTy*lVlWnoxN7UelXfJAXOreXLGqUKXSpqxR-1B3FTY6lbnVTY-AOfcoHTaotLGY41-RYjbAoyrS-sLvtk8pTAAoGya47TGavU2fQwQp7juTlzV0wn8KF2ExL*iCb7gREFJfvW93L4eT2I8DnAXn6ahdmnXNs7rrgtelqJsNQJREURLH47hmKxmMzvt4t149Dk5aPOjLOzBhd5zxgba6OWJp*sCjwMFj9Gdc58v5BtioW6M_";

    String mIMLoginUserId;
    String mIMLoginUserSig;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        mLoginPanel.setLoginEvent(this);
        testUserName();
        mAutoLogin = getIntent().getBooleanExtra(Constants.AUTO_LOGIN, false);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        mPresenter = new PojoLoginPresenter(this);
        TalkActivity.init = false;
        checkPermission();
        if (mAutoLogin) {
            if (TIMManager.getInstance().isInited()) {
                mFlashView.setVisibility(View.VISIBLE);
                mFlashView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mFlashView.setVisibility(View.GONE);
                    }
                }, 1000);
            }
        } else {
            mFlashView.setVisibility(View.GONE);
        }
    }

    private void testUserName() {
//        mSpinner = findViewById(R.id.user_id_spinner);
        adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_dropdown_item, getDataSource());
        mSpinner.setAdapter(adapter);
        mSpinner.setOnItemSelectedListener(this);

//        mBtnLoginIm = (Button)findViewById(R.id.loginim_btn);
        mBtnLoginIm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPresenter.imLoginForDev(mIMLoginUserId, mIMLoginUserSig, true);
            }
        });
    }

    private List<String> getDataSource() {
        List<String> list = new ArrayList<String>();
        list.add(userId_1);
        list.add(userId_2);
        list.add(userId_3);
        return list;
    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
        String item = (String) mSpinner.getItemAtPosition(position);
        Log.e("vinson", "position = " + position + ", item " + item);
        mIMLoginUserId = item;
        if (position == 0) {
            mIMLoginUserSig = userSig_1;
        } else if (position == 1) {
            mIMLoginUserSig = userSig_2;
        } else if (position == 2) {
            mIMLoginUserSig = userSig_3;
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }

    private static final int REQ_PERMISSION_CODE = 0x100;
    PojoLoginPresenter mPresenter;
    private boolean mAutoLogin;
    View mFlashView;

    @Override
    protected void onNewIntent(Intent intent) {
        TalkActivity.init = false;
        super.onNewIntent(intent);
    }

    //从本地缓存里获取用户信息
    private void initCache() {
        SharedPreferences shareInfo = getApplication().getSharedPreferences(Constants.USERINFO, 0);
        String account = shareInfo.getString(Constants.ACCOUNT, "");
        String password = shareInfo.getString(Constants.PWD, "");
        ((LoginView) mLoginPanel).getAccountEditor().setText(account);
        ((LoginView) mLoginPanel).getAccountEditor().requestFocus();
        ((LoginView) mLoginPanel).getPasswordEditor().setText(password);
        if (TextUtils.isEmpty(account)) {
            mLoginPanel.setModel(false);
        } else {
            if (mAutoLogin) {
                mPresenter.login(account, password);
            }
        }
    }

    @Override
    public void onLoginClick(View view, String userName, String password) {
        //往业务服务器发起登录请求
        mPresenter.login(userName, password);

        // 这里省去了去业务服务器发起登录请求的流程，直接登陆IM
//        mPresenter.imLoginForDev(userName, userSig, true);

    }

    @Override
    public void onRegisterClick(View view, String userName, String password) {
        mPresenter.register(userName, password);
    }


    @Override
    public void onLoginSuccess(Object res) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(((LoginView) mLoginPanel).getPasswordEditor().getWindowToken(), 0);
        Intent intent = new Intent(this, TalkActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void onLoginFail(String module, int errCode, String errMsg) {
        UIUtils.toastLongMessage("登录失败：" + errMsg);
    }

    @Override
    public void onRegisterSuccess(Object res) {
        UIUtils.toastLongMessage("注册成功");
        Intent intent = new Intent(this, TalkActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void onRegisterFail(String module, int errCode, String errMsg) {
        UIUtils.toastLongMessage("注册失败：" + errMsg);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            TalkActivity.exitApp();
            finish();
        }
        return true;

    }

    //权限检查
    private boolean checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> permissions = new ArrayList<>();
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA)) {
                permissions.add(Manifest.permission.CAMERA);
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.RECORD_AUDIO)) {
                permissions.add(Manifest.permission.RECORD_AUDIO);
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_PHONE_STATE)) {
                permissions.add(Manifest.permission.READ_PHONE_STATE);
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE)) {
                permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            }
            if (permissions.size() != 0) {
                String[] permissionsArray = permissions.toArray(new String[1]);
                ActivityCompat.requestPermissions(this,
                        permissionsArray,
                        REQ_PERMISSION_CODE);
                return false;
            }
        }

        return true;
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }
}
